#include "main.h"


/*全局变量*/
char mobilebuf[size];//移动端和服务端通信的字符串
char validdata[7];//有效的7个字节数据
MSG msg;
INFO info;

int main(void)
{
	int fd;
	int ret;
	char* cmd_ker;//命令关键字，解析关键字即可知道整个命令是什么

	/*与服务器建立连接*/
	struct sockaddr_in server;
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr("192.168.104.221");//开发板IP
	server.sin_port = htons(12345);

	START:
	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) 
	{
		perror("socket");
		exit(1);
	}

	ret = connect(fd, (struct sockaddr*)&server, sizeof(server));	
	if (ret == -1)
	{
		perror("connect");
		exit(1);
	}

	/*输入命令并发送*/
	print_user();
	printf("输入命令>>");
	scanf("%[^\n]",mobilebuf);
	write(fd,mobilebuf,size);

	/*解析命令并调用对应函数*/
	strtok(mobilebuf," ");
	cmd_ker = strtok(NULL," ");//cmd_ker是命令字符串的第2个词
	
	if (strncmp(cmd_ker, "login", 5)== 0)//登录命令
	{
		ret = login(fd);
		if(ret == 0)
			goto APP;
		else
		{
			while (getchar() != '\n');//清空标准输入缓冲区
			goto START;
		}
	}
	else if (strncmp(cmd_ker, "register", 8)== 0)//注册命令
	{
		regis(fd);
		while (getchar() != '\n');//清空标准输入缓冲区
		goto START;
	}
	else if (strncmp(cmd_ker, "quit", 4)== 0)//退出命令
	{
		close(fd);
		return 0;
	}
	else
	{
		printf("无法识别的命令。请重新输入。\n");
		close(fd);
		goto START;
	}

	APP:
	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) 
	{
		perror("socket");
		exit(1);
	}

	ret = connect(fd, (struct sockaddr*)&server, sizeof(server));	
	if (ret == -1)
	{
		perror("connect");
		exit(1);
	}

	print_app();
	printf("输入命令>>");
	bzero(mobilebuf,size);
	fflush(stdin);//fflush失效了，没有真的把缓冲区刷新！
	while(getchar() != '\n');
	scanf("%[^\n]",mobilebuf);
	fflush(stdin);
	write(fd,mobilebuf,size);

	/*解析命令并调用对应函数*/
	strtok(mobilebuf," ");
	cmd_ker = strtok(NULL," ");//cmd_ker是命令字符串的第2个词
	
	if(strncmp(cmd_ker, "mac", 3) == 0)//控制设备命令		
		control(fd);
	else if (strncmp(cmd_ker, "monitor", 12) == 0)//获取参数请求
		req_paras(fd);//服务器判断客户端是否有权限获取参数
	else if(strncmp(cmd_ker, "monitor_info", 12) == 0)//获取参数正文
		get_paras(fd);
	else if(strncmp(cmd_ker, "stop_moninfo_send", 17) == 0)//结束获取参数
		printf("向服务端发送参数结束请求\n");
	else if (strncmp(cmd_ker, "quit", 4) == 0)//退出命令
	{
		close(fd);
		return 0;
	}
	else
	{
		printf("无法识别的命令。请重新输入。\n");
		close(fd);
		goto START;
	}

	goto APP;

	return 0;
}
